/*
  Build assets: copy less sources to dist/less, compile to css in dist/style,
  and generate dist/types/global.d.ts listing exported components.
*/
const fs = require('fs')
const path = require('path')
const less = require('less')

const root = path.resolve(__dirname, '..')
const srcDir = path.join(root, 'src')
const distDir = path.join(root, 'dist')
const outLessDir = path.join(root, 'less')
const outStylesDir = path.join(root, 'styles')
const outTypesDir = path.join(root, 'types')

function ensureDir(dir) {
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true })
}

function walk(dir, predicate) {
  const out = []
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
    const full = path.join(dir, entry.name)
    if (entry.isDirectory()) out.push(...walk(full, predicate))
    else if (!predicate || predicate(full)) out.push(full)
  }
  return out
}

async function renderLessToCss(lessFile, cssFile) {
  const code = fs.readFileSync(lessFile, 'utf8')
  const res = await less.render(code, { filename: lessFile })
  ensureDir(path.dirname(cssFile))
  fs.writeFileSync(cssFile, res.css)
}

async function main() {
  // 1) Copy less sources
  ensureDir(outLessDir)
  ensureDir(outStylesDir)

  // Copy root less files
  const srcStylesDir = path.join(srcDir, 'styles')
  const rootLessFiles = ['index.less', 'variable.less']
  // variable.less: copy and compile to styles/variable.css
  const variableSrc = path.join(srcStylesDir, 'variable.less')
  if (fs.existsSync(variableSrc)) {
    const variableOut = path.join(outLessDir, 'variable.less')
    ensureDir(path.dirname(variableOut))
    fs.copyFileSync(variableSrc, variableOut)
    await renderLessToCss(variableSrc, path.join(outStylesDir, 'variable.css'))
  }

  // Copy component less files
  const srcComponentsDir = path.join(srcDir, 'components')
  if (fs.existsSync(srcComponentsDir)) {
    const lessFiles = walk(srcComponentsDir, (p) => p.endsWith('.less'))
    for (const from of lessFiles) {
      const rel = path.relative(srcComponentsDir, from)
      const toLess = path.join(outLessDir, 'components', rel)
      ensureDir(path.dirname(toLess))
      // read and rewrite variable import to new layout (less/variable.less)
      let code = fs.readFileSync(from, 'utf8')
      code = code.replace(/@import\s+["']([^"']*?)styles\/variable\.less["'];/g, (m, p1) => {
        const rewritten = `@import "${p1}variable.less";`
        return rewritten
      })
      code = code.replace(/@import\s+["']~?@\/styles\/variable\.less["'];/g, '@import "../../variable.less";')
      fs.writeFileSync(toLess, code)
      // compile to css under style/components from the rewritten file
      const toCss = path.join(outStylesDir, 'components', rel.replace(/\.less$/, '.css'))
      await renderLessToCss(toLess, toCss)
    }
  }

  // Generate less/index.less that imports variable and all component less
  const generatedIndexLess = []
  if (fs.existsSync(path.join(outLessDir, 'variable.less'))) {
    generatedIndexLess.push("@import \"./variable.less\";")
  }
  // collect component .less files for import (relative to less/ root)
  const lessComponentDir = path.join(outLessDir, 'components')
  if (fs.existsSync(lessComponentDir)) {
    const componentLessFiles = walk(lessComponentDir, (p) => p.endsWith('.less'))
    // stable order
    componentLessFiles.sort()
    for (const file of componentLessFiles) {
      const relFromLess = path.relative(outLessDir, file).split(path.sep).join('/')
      generatedIndexLess.push(`@import \"./${relFromLess}\";`)
    }
  }
  const indexLessPath = path.join(outLessDir, 'index.less')
  ensureDir(path.dirname(indexLessPath))
  fs.writeFileSync(indexLessPath, generatedIndexLess.join('\n'))
  // Compile styles/index.css from generated less/index.less
  await renderLessToCss(indexLessPath, path.join(outStylesDir, 'index.css'))

  // 2) Generate dist/types/global.d.ts
  ensureDir(outTypesDir)
  const typeContent = `// Generated global component types\ndeclare module 'vue' {\n  export interface GlobalComponents {\n    MyButton: typeof import('mings-ui')['MyButton']\n    MePanel: typeof import('mings-ui')['MePanel']\n    MePanelTitle: typeof import('mings-ui')['MePanelTitle']\n    MePanelContent: typeof import('mings-ui')['MePanelContent']\n  }\n}\nexport {}\n`
  fs.writeFileSync(path.join(outTypesDir, 'global.d.ts'), typeContent)

  console.log('Assets built: less/index.less, less/variable.less, styles/index.css, styles/variable.css, types/global.d.ts')
}

main().catch((err) => {
  console.error(err)
  process.exit(1)
})


